package com.edu.controller.user;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.edu.dto.ResultDto;
import com.edu.entity.UserEntity;
import com.edu.service.UserService;
import com.edu.service.impl.UserServiceImpl;
import com.edu.utils.JwtUtils;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Map;

/**
 * 根据用户id获取单一用户所有信息的Servlet类
 * 该类继承自HttpServlet，处理来自客户端的用户信息请求。
 */
@WebServlet(urlPatterns = "/users/*")
public class UserController extends HttpServlet {
    UserService userService;

    /**
     * 初始化方法。
     * 在Servlet生命周期中被调用，用于初始化userService实例。
     */
    public UserController() {
        this.userService = new UserServiceImpl();
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getPathInfo().substring(1);
        JSONObject requestBody = ServletHelper.getRequestBodyAsJson(req);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        //从请求头获取token
        String token = req.getHeader("token");
        Map<String, Object> user = JwtUtils.validateToken(token);

        try {
            if(user != null && user.get("role").equals("admin")){
                Integer resultRow = userService.deleteUserInfo(userId);

                if (resultRow >= 1) {
                    String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "User information delete successfully.");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                } else {
                    String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "用户不存在");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                }
            } else {
                String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "权限不足");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getPathInfo().substring(1);
        JSONObject requestBody = ServletHelper.getRequestBodyAsJson(req);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        String newUsername = requestBody.getString("username");
        String newEmail = requestBody.getString("email");
        String oldPassword = requestBody.getString("oldPassword");
        String newPassword = requestBody.getString("newPassword");

        try {
            Integer resultRow = userService.updateUserInfo(userId, newUsername, newEmail, oldPassword, newPassword);

            if (resultRow >= 1) {
                String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "User information updated successfully.");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "更新失败。用户名或密码无效。");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 获取用户id
        int userId = Integer.parseInt(request.getPathInfo().substring(1));
        System.out.println("获取到的用户id: " + userId);

        // 根据用户id查询用户信息
        UserEntity userInfo = userService.getUserInfoById(userId);

        if (userInfo != null) {
            String rst = ResultDto.success(userInfo);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(rst);
        } else {
            String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "获取用户信息失败。用户id无效。");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(rst);
        }
    }
}
